<template>
  <div class="member-list">
    <a-form class="search-form">
      <a-row :gutter="24">
        <a-col :lg="8" :xl="5" :xxl="3">
          <a-form-item label="账号状态">
            <a-select v-model="enableType">
              <a-select-option value="0">全部</a-select-option>
              <a-select-option value="1">关闭</a-select-option>
              <a-select-option value="2">启用</a-select-option>
              <!-- 搜索类型  0 全部 1 id 2 账号 3 手机号 -->
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :lg="16" :xl="8" :xxl="7">
          <a-form-item label>
            <a-input-group class="query-item" compact>
              <a-select style="width: 35%" v-model="searchStatus">
                <a-select-option value="0">全部</a-select-option>
                <a-select-option value="1">商户号</a-select-option>
                <a-select-option value="2">商户名称</a-select-option>
                <a-select-option value="3">店铺名称</a-select-option>
                <a-select-option value="4">商户手机号</a-select-option>
              </a-select>
              <a-input style="width: 65%" placeholder="请输入查询条件" v-model="keywords" />
            </a-input-group>
          </a-form-item>
        </a-col>
        <a-col :lg="10" :xl="10" :xxl="7">
          <a-form-item label="上架时间">
            <a-range-picker
              :placeholder="['开始时间', '结束时间']"
              class="select-range-time"
              @change="getCreateTime"
              v-model="createTime"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :lg="14" :xl="10" :xxl="7">
          <a-form-item label="所属区域">
            <area-select :createPlace="area" @handlePlace="selectArea" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :xl="10" :xxl="12" class="top-btns">
          <a-button type="primary" html-type="submit" @click="searchListData">查询</a-button>
          <a-button @click="resetList">重置</a-button>
          <a-button type="primary" @click="exportList">
            <a-icon type="download" />导出
          </a-button>
          <a-button type="primary" @click="Code()" :loading="downCodeLoading">收款码</a-button>
          <a-button type="primary" @click="TableCode()" :loading="downTableLoading">桌面收款码</a-button>
          <a-button type="primary" @click="down()" :loading="downLoading">所有收款码</a-button>
          <a-button type="primary" @click="outputCode()" :loading="outputCodeLoading">导出二维码</a-button>
        </a-col>
      </a-row>
    </a-form>
    <div class="search-result-list">
      <a-table
        :columns="columns"
        :dataSource="merchantListData"
        rowKey="id"
        :pagination="pagination"
        :loading="loading"
        :scroll="scrollX"
      >
        <span slot="is_enable" slot-scope="value, item">
          <a-switch
            checkedChildren="开"
            unCheckedChildren="关"
            :defaultChecked="parsevalue(value)"
            @change="isEnableKG(item)"
            disabled
          />
        </span>
        <template slot="code_url" slot-scope="value">
          <img :src="getQrcode(value)" class="code-img" @click="showImg(value)" />
        </template>
        <span slot="action" slot-scope class="action-wrap">
          <a>查看详情</a>
          <a>钱包</a>
          <a>优惠券</a>
        </span>
      </a-table>
      <pagination ref="pageBand" :total="total" @loadDataList="pageInit" />
    </div>
    <div class="full-screen-wrap" v-show="showCodeImg" @click="showCodeImg=false">
      <div class="code-img" id="codeImg"></div>
    </div>
    <div class="modal-wrap">
      <!-- 导出弹窗 -->
      <export-list ref="exportBand" exportApi="merchantList" exportTxt="请选择商户上架时间(非必选):" />
    </div>
  </div>
</template>
<script>
import { merchantList } from '../../store/merchantApi.js'
import jrQrcode from 'jr-qrcode'
import { SynthesisPhoto } from '../../utils/compositePicture'
// 下载和压缩收款码的依赖
import { saveAs } from 'file-saver'
import JSZip from 'jszip'
import { Promise } from 'q'
import { debuglog } from 'util'
export default {
  name: 'MerchantList',
  data() {
    return {
      showCodeImg: false,
      total: 0,
      start_time: 0,
      end_time: 0,
      keywords: '',
      num: 10,
      visible: false,
      pagination: false,
      loading: false,
      searchStatus: '0',
      createTime: [],
      area: [],
      enableType: '0',
      scrollX: {},
      columns: [
        {
          dataIndex: 'index',
          title: '序号',
          fixed: 'left',
          width: 60
        },
        {
          title: '商户id',
          dataIndex: 'id',
          fixed: 'left',
          width: 80
        },
        {
          title: '商户号',
          dataIndex: 'merchant_no'
        },
        {
          title: '商户名称',
          dataIndex: 'merchant_name'
        },
        {
          title: '店铺名称',
          dataIndex: 'store_name'
        },
        {
          title: '商户收款码',
          dataIndex: 'code_url',
          scopedSlots: { customRender: 'code_url' }
        },
        {
          title: '商户手机号',
          dataIndex: 'phone'
        },
        {
          title: '分类',
          dataIndex: 'type'
        },
        {
          title: '省份',
          dataIndex: 'province_name'
        },
        {
          title: '城市',
          dataIndex: 'city_name'
        },
        {
          title: '区/县',
          dataIndex: 'district_name'
        },
        {
          title: '结算费率',
          dataIndex: 'settle_rate'
        },
        {
          title: '上架时间',
          dataIndex: 'created_at'
        },
        {
          title: '状态',
          dataIndex: 'is_enable',
          scopedSlots: { customRender: 'is_enable' }
        },
        {
          title: '操作',
          fixed: 'right',
          dataIndex: 'action',
          width: 200,
          scopedSlots: { customRender: 'action' }
        }
      ],
      merchantListData: [],
      options: [],
      test: '',
      codeBg: require('../../assets/images/code-bg.png'),
      code: require('../../assets/images/code.png'),
      tableCode: require('../../assets/images/tableCode.png'),
      testList: [],
      downLoading: false,
      downTableLoading: false,
      downCodeLoading: false,
      outputCodeLoading: false,
      selectedOptions:[]
    }
  },
  methods: {
    // 导出二维码
    outputCode(record) {
      if (this.total) {
        this.outputCodeLoading = true
        const zip = new JSZip()
        const condition = Math.ceil(this.total / 20)
        let promisearr = []
        for (let i = 1; i <= condition; i++) {
          const params = {
            page: i,
            pageSize: 20
          }
          promisearr.push(this.pageInit(params, false))
        }
        Promise.all(promisearr).then(res => {
          res.forEach((item, index) => {
            item.forEach(({ merchant_name, code_url }) => {
              let data = this.getQrcode(code_url)
              zip.file(
                `${merchant_name}-${this.guid()}.png`,
                data.replace('data:image/png;base64,', ''),
                {
                  base64: true
                }
              )
            })
            if (index === res.length - 1) {
              zip.generateAsync({ type: 'blob' }).then(content => {
                let area = ''
                this.selectedOptions.map(({ name }) => {
                  area += name
                })
                saveAs(content, `${area}二维码${this.guid()}.zip`)
                this.outputCodeLoading = false
              })
            }
          })
        })
      } else {
        this.$message.warning('暂无商家数据，请稍后下载')
      }
    },
    // 所有收款码
    down() {
      if (this.merchantListData.length) {
        this.downLoading = true
        let tableCode = this.downTableCode()
        let code = this.downCode()
        this.mergeImg([...tableCode, ...code])
      } else {
        this.$message.warning('暂无商家数据，请稍后下载')
      }
    },
    // 收款码
    Code() {
      if (this.merchantListData.length) {
        this.downCodeLoading = true
        let code = this.downCode()
        Promise.all(code).then(res => {
          this.zipImg('收款码', res)
        })
      } else {
        this.$message.warning('暂无商家数据，请稍后下载')
      }
    },
    //下载收款码
    downCode() {
      let params = {
        width: 472,
        height: 669,
        bg: this.codeBg,
        codeWidth: '42%',
        codePos: {
          x: 410,
          y: 750
        },
        namePos: {
          x: 0,
          y: 1360
        }
      }
      return this.allPromiseImg(params)
    },
    // 合并数据
    mergeImg(codeList) {
      Promise.all(codeList).then(res => {
        let tableCode = res.slice(0, res.length / 2)
        let code = res.slice(res.length / 2, res.length)
        code.forEach(item => {
          tableCode.forEach(childItem => {
            if (item.name === childItem.name) {
              item.tableCode = childItem.url
            }
          })
        })
        this.zipImg('所有收款码', code)
      })
    },
    // 桌面收款码
    TableCode() {
      if (this.merchantListData.length) {
        this.downTableLoading = true
        let code = this.downTableCode()
        Promise.all(code).then(res => {
          this.zipImg('桌面收款码', res)
        })
      } else {
        this.$message.warning('暂无商家数据，请稍后下载')
      }
    },
    // 下载桌面收款码
    downTableCode() {
      let params = {
        width: 393,
        height: 393,
        bg: this.tableCode,
        codeWidth: '36.1%',
        fontSize: '26px',
        codePos: {
          x: 378,
          y: 410
        },
        namePos: {
          x: 0,
          y: 850
        }
      }
      return this.allPromiseImg(params)
    },
    // 获取当前页所有二维码
    getCodeImg() {
      let codeList = this.merchantListData.map(item => {
        return {
          url: this.getQrcode(item.code_url),
          store_name: item.store_name,
          merchant_name: item.merchant_name
        }
      })
      return codeList
    },
    // allPromiseImg
    allPromiseImg(params) {
      let allPromiseImg = this.getCodeImg().map(
        ({ url, merchant_name, store_name }) => {
          params.code = url
          params.merchant_name = merchant_name
          params.store_name = store_name
          return SynthesisPhoto(params)
        }
      )
      return allPromiseImg
    },
    // 压缩图片
    zipImg(zipName, codeList) {
      const zip = new JSZip()
      codeList.forEach(({ merchant_name, url, tableCode }, index) => {
        if (zipName === '所有收款码') {
          const img = zip.folder(merchant_name)
          img.file(
            `${merchant_name}-收款码${this.guid()}.png`,
            url.replace('data:image/png;base64,', ''),
            {
              base64: true
            }
          )
          img.file(
            `${merchant_name}-桌面收款码${this.guid()}.png`,
            tableCode.replace('data:image/png;base64,', ''),
            {
              base64: true
            }
          )
        } else {
          let data = tableCode || url
          zip.file(
            `${merchant_name}-桌面收款码${this.guid()}.png`,
            data.replace('data:image/png;base64,', ''),
            {
              base64: true
            }
          )
        }
        if (index === codeList.length - 1) {
          zip.generateAsync({ type: 'blob' }).then(content => {
            saveAs(content, `${zipName}.zip`)
            if (zipName === '所有收款码') {
              this.downLoading = false
            } else if (zipName === '收款码') {
              this.downCodeLoading = false
            } else if (zipName === '桌面收款码') {
              this.downTableLoading = false
            }
          })
        }
      })
    },
    guid() {
      function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
      }
      return (
        S4() +
        S4() +
        '-' +
        S4() +
        '-' +
        S4() +
        '-' +
        S4() +
        '-' +
        S4() +
        S4() +
        S4()
      )
    },
    showImg(text) {
      this.showCodeImg = true
      document.getElementById(
        'codeImg'
      ).innerHTML = `<img src="${jrQrcode.getQrBase64(text)}">`
    },
    getQrcode(text) {
      return jrQrcode.getQrBase64(text)
    },
    // 省市区选择
    selectArea({ area, provinceId, cityId, districtId, selectedOptions }) {
      this.area = area
      this.provinceId = provinceId
      this.cityId = cityId
      this.districtId = districtId
      this.selectedOptions = selectedOptions
    },
    parsevalue(value) {
      return JSON.parse(value)
    },
    // 列表和筛选接口
    pageInit(info, flag = true) {
      return new Promise((resolve, reject) => {
        if (this.flag) {
          this.loading = true
        }
        var data = {
          searchType: this.searchStatus,
          page: info.page,
          num: info.pageSize,
          enableType: this.enableType
        }
        if (this.start_time != 0) {
          data.startTime = this.start_time
        }
        if (this.end_time != 0) {
          data.endTime = this.end_time
        }
        if (this.keywords !== '') {
          data.name = this.keywords
        }
        if (this.provinceId != '') {
          data.provinceId = this.provinceId
        }
        if (this.cityId != '' || this.cityId == undefined) {
          data.cityId = this.cityId
        }
        if (this.districtId != '' || this.districtId == undefined) {
          data.districtId = this.districtId
        }
        merchantList(data)
          .then(res => {
            if (flag) {
              var array = res.data.list
              for (let i = 0; i < array.length; i++) {
                array[i]['index'] = (info.page - 1) * info.pageSize + (i + 1)
              }
              this.merchantListData = array
              if (res.data.list.length > 0) {
                this.scrollX = { x: 2500 }
              } else {
                this.scrollX = {}
              }
              this.total = res.data.total_num
              this.loading = false
            } else {
              resolve(res.data.list)
            }
          })
          .catch(error => {
            reject()
          })
      })
    },
    // 按条件查询
    searchListData() {
      this.$refs.pageBand.getData()
    },
    // 重置
    resetList() {
      this.searchStatus = '0'
      this.provinceId = ''
      this.cityId = ''
      this.districtId = ''
      this.createTime = []
      this.area = []
      this.start_time = 0
      this.end_time = 0
      this.defaultSearch = '0'
      this.keywords = ''
      this.selectedOptions = []
      this.$refs.pageBand.getData()
    },
    // 获取时间戳
    getCreateTime(date, str) {
      if (str[0] && str[1]) {
        this.start_time = new Date(str[0] + ' 00:00:00').getTime() / 1000
        this.end_time = new Date(str[1] + ' 23:59:59').getTime() / 1000
      } else {
        this.start_time = 0
        this.end_time = 0
      }
    },
    // 开关操作
    isCommissionKG(checked) {
      console.log(checked, 'is_commissin')
    },
    isEnableKG(checked) {
      console.log(checked, 'is_enable')
    },
    // 导出按钮弹出弹窗
    exportList() {
      this.$refs.exportBand.openPop()
    }
  }
}
</script>
<style>
</style>
